﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DotNet.DevOps.Tasks.Util
{
    internal static class FilePropertyExtensions
    {
        internal static IEnumerable<String> GetValidFilenames(this String @this)
        {
            var filenames = new List<String>();
            ExtractFilenames(@this).ForEach(filenames.Add);

            ReplaceWildcardFilenames(filenames);

            filenames.ForEach(CheckIfExists);

            return filenames;
        }

        private static void ReplaceWildcardFilenames(List<string> filenames)
        {
            var wildcardNames = filenames.Where(x => x.Contains("*")).ToList();

            var wildcardFilenames = new List<string>();
            wildcardNames.ForEach(wildcard => ScanWildcard(wildcard, wildcardFilenames));

            wildcardNames.ForEach(wildcard => filenames.Remove(wildcard));

            filenames.AddRange(wildcardFilenames);
        }

        private static void ScanWildcard(String wildcardToScan, List<String> wildcardFilenames)
        {
            wildcardFilenames.AddRange(Enumerable.ToList<string>(Directory.EnumerateFiles(Environment.CurrentDirectory, wildcardToScan, SearchOption.AllDirectories)));
        }

        private static List<String> ExtractFilenames(String files)
        {
            CheckIfNull(files);

            return files.Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        private static void CheckIfNull(String files)
        {
            if (String.IsNullOrEmpty(files))
            {
                throw new Exception("No filename(s) specified.");
            }
        }

        private static void CheckIfExists(String file)
        {
            if (File.Exists(file) == false)
            {
                throw new Exception(String.Format("Cannot find the file {0}", file));
            }
        }
    }
}
